var tableElem = "LAY-home-productCategory-list";
var formElem = "LAY-home-productCategory-listform";
var tableToolsElem = "LAY-home-productCategory-tools";
var formSubmitElem = "LAY-home-productCategory-listform-submit";
var formUrl = '/home/productCategory/listform'
var historyUrl = '/home/productCategory/list'
var baseUrl = window.globalConfig.url_productCategory

layui.use(['common'], function (common) {
    var $ = layui.$
        , admin = layui.admin
        , treeTable = layui.treeTable
        , form = layui.form
    ;

    //列表管理
    var tableItem = treeTable.render({
        elem: `#${tableElem}`
        , url: baseUrl
        , tree: {
            customName: {}
        }
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'id', width: 100, title: 'id', fixed: 'left', sort: true}
            , {field: 'name', title: '分类名称', minWidth: 250, edit: 'text'}
            , {field: 'rewrite_url', title: '自定义URL', minWidth: 250, edit: 'text'}
            , {field: 'is_show', title: '是否显示', templet: "#ID-table-productCategory-is_show-switch"}
            , {field: 'sort', title: '排序', edit: 'text'}
            , {title: '操作', minWidth: 380, align: 'center', fixed: 'right', toolbar: `#${tableToolsElem}`}
        ]]
        , page: true
        , limit: 10
        , limits: [10, 15, 20, 25, 30]
        , text: {none: '暂无数据！'}
    });

    var active = {
        //添加
        add: function (othis) {
            location.hash = formUrl
        }
    };

    $('.layui-btn.layuiadmin-btn-list').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    // 增删改查
    treeTable.on(`tool(${tableElem})`, function (obj) {
        var data = obj.data;
        if (obj.event === 'del') { // 删除列表
            layer.confirm('确定删除此列表？', function (index) {
                admin.req({
                    url: baseUrl + "/" + data.id,
                    type: "DELETE",
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        layer.close(index);
                        tableItem.reloadData(); //重载表格
                    }
                })
            });
        } else if (obj.event === 'edit') {// 修改列表
            location.hash = formUrl + "/parent_id=" + data.parent_id + "/id=" + data.id
        } else if (obj.event === 'add') {
            location.hash = formUrl + "/parent_id=" + data.id
        } else if (obj.event === 'copy') {
            layer.confirm('确定复制此产品？', function (index) {
                var field = data
                field.name = field.name + "_" + common.generateRandomRewriteUrl(4)
                field.rewrite_url = common.generateRandomRewriteUrl(16)
                delete field.id
                admin.req({
                    url: baseUrl,
                    type: "POST",
                    data: field,
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        if (res.code === 0) {
                            tableItem.reloadData()
                        }
                    }
                })
            });

        }
    });

    /**
     * 表单回调
     * @param d
     */
    layui.data.done = function (d) {
        var remoteData = d.data;
        form.render();
        // 加载上传插件
        // common.uploader('ID-upload-productCategory-btn', 'ID-upload-productCategory-img', 'cover_img')
        // common.uploader('ID-upload-productCategory-inner_img-btn', 'ID-upload-productCategory-inner_img-img', 'inner_img')

        // 加载下拉框
        common.formDropdownEditor(
            window.globalConfig.url_navigate_list,
            'navName',
            'navId',
            'navName'
        )
        if (!remoteData.id) {
            $("#rewrite_url").val(common.generateRandomRewriteUrl(16))
        }

        // 只需要添加这里就能添加富文本的添加
        // let editors = {
        //     // 'editor': 'desc',
        //     'inner_content-editor': 'inner_content',
        // }
        // common.loadEditors(remoteData,editors)


        // 加载字段关联的穿梭框
        let productCatFieldsId = "ID-transfer-products-category-fields"
        let $fields_ids = [];
        if (remoteData.relationFields) {
            $fields_ids = remoteData.relationFields.map(item => item.id)
        }
        common.ctmTransfer(
            window.globalConfig.url_productsFields,
            productCatFieldsId,
            'id',
            'name',
            $fields_ids
        );

        // 加载 关联页面
        common.formDropdownEditor(
            `${window.globalConfig.url_page_list}?all=1`,
            "pageName",
            "pageId",
            "pageName",
            "page_id",
            "title"
        )

        // 添加分类
        form.on(`submit(${formSubmitElem})`, (data) => {
            var field = data.field; //获取提交的字段
            field.is_show = field.is_show === undefined ? 0 : 1;

            // field = common.getEditorsContent(field, editors)

            field.fields_ids = common.getCtmTransferData(productCatFieldsId)


            let url = baseUrl;
            let type = "POST";
            if (remoteData && remoteData.id) {
                url += "/" + remoteData.id;
                type = "PUT"
            }

            //提交 Ajax 成功后，关闭当前弹层并重载表格
            admin.req({
                url: url,
                type: type,
                data: field,
                success: function (res) {
                    if (res.code === 0) {
                        history.back()
                    }
                    common.ctmMsg(res.code, res.msg)
                }
            })
        })


        //页面选择
        common.formDropdownEditor(
            window.globalConfig.url_page_list,
            'pageName',
            'pageId',
            'pageName',
            'page_id'
        )
    }

    // 表格文本修改
    common.tableTextEditor(tableElem, baseUrl, 'id')
    common.tableSwitchEditor('productCategory-is_show-status', baseUrl, 'id')
});